const SEARCH_KEY = 'search-list'

const HISTORY_MAX = 10

export default {
	namespaced: true,
	state: () => {
		return {
			searchData: uni.getStorageSync(SEARCH_KEY) || []
		}
	},
	mutations: {
		saveToStorage(state) {
			uni.setStorage({
				key: SEARCH_KEY,
				data: state.searchData
			})
		},
		// 添加数据
		saveSearchData(state, val) {
			const index = state.searchData.findIndex((item) => item === val)
			if (index !== -1) {
				state.searchData.splice(index, 1)
			}
			state.searchData.unshift(val)
			// 判断是否超过了最大缓存数量
			if (state.searchData.length > HISTORY_MAX) {
				state.searchData.splice(HISTORY_MAX - 1, state.searchData.length - HISTORY_MAX - 1);
			}
			this.commit('search/saveToStorage')
		},
		// 数据删除
		onRemoveSearchData(state, index) {
			state.searchData.splice(index, 1);
			this.commit('search/saveToStorage')
		},
		onRemoveAllSearchData(state) {
			state.searchData = [];
			this.commit('search/saveToStorage')
		}
	}
}
